package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog3Vo;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private RedissonClient redisson;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getCategoryListTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect = categoryEntities
                .stream()
                .filter(category -> category.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getCategoryChildren(menu,categoryEntities));
                    return menu;
                })
                .sorted((menu1, menu2) ->
                        (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort())
                )
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        //
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> ids = new ArrayList<>();
        CategoryEntity category = this.getById(catelogId);

        while (category.getParentCid() != 0){
            ids.add(category.getCatId());
            category = this.getById(category.getParentCid());
        }

        ids.add(category.getCatId());
        Collections.reverse(ids);

        return ids.toArray(new Long[ids.size()]);
    }
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            System.out.println(category.getName());
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }
    //每一个需要缓存的数据我们都来制定要放到哪个名字的缓存【缓存分区（按照业务类型分）】
    @Cacheable(value = {"category"},key = "#root.method.name")
    //代表当前方法的结果需要缓存，如果缓存中有，方法不调用，如果没有，会调用方法，最后将方法的结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        List<CategoryEntity> allCategory = this.list(null);
        //获取所有一级目录
        List<CategoryEntity> level1Category = allCategory.stream()
                .filter(item -> item.getParentCid() == 0)
                .collect(Collectors.toList());

        Map<String, List<Catelog2Vo>> stringListMap = new HashMap<>();
        level1Category.stream().forEach(l1 -> {

//            QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("parent_cid", l1.getCatId());
            List<CategoryEntity> level2Category = getCategory(allCategory, l1.getCatId());
            List<Catelog2Vo> catelog2Vos = level2Category.stream().map(l2 -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo();
                catelog2Vo.setId(l2.getCatId().toString());
                catelog2Vo.setCatalog1Id(l1.getCatId().toString());
                catelog2Vo.setName(l2.getName());
//                QueryWrapper<CategoryEntity> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.eq("parent_cid", l2.getCatId());
                List<CategoryEntity> level3Category = getCategory(allCategory, l2.getCatId());
                List<Catelog3Vo> catelog3Vos = level3Category.stream().map(l3 -> {
                    Catelog3Vo catelog3Vo = new Catelog3Vo();
                    catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                    catelog3Vo.setId(l3.getCatId().toString());
                    catelog3Vo.setName(l3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(catelog3Vos);
                return catelog2Vo;
            }).collect(Collectors.toList());
            stringListMap.put(l1.getCatId().toString(), catelog2Vos);
        });
        return stringListMap;
    }

    //TODO 产生堆外内存溢出OutOfDirectMemberError
    //1)、springboot2.0后默认试用lettuce作为操作redis客户端，试用netty进行网络通信
    //2）、lettuce的bug导致堆外内存溢出 -Xmx300m，netty如果没有指定堆外内存，默认使用-Xmx300m
    //解决方案：不能只取调大堆外内存。
    //  1.升级lettuce客户端 2.切换使用jedis
//    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        /**
         * 1.空结果缓存：解决缓存穿透
         * 2.设置过期时间（加随机值）：解决缓存雪崩问题
         * 3.加锁：解决缓存击穿
         */
        String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
        if (StringUtils.isEmpty(catelogJSON)){
            Map<String, List<Catelog2Vo>> catelogJsonFromDb =
                    getCatelogJsonFromDbWithRedisLock();


            return catelogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> parseObject = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return parseObject;

    }

    /**
     * 缓存里的数据如何和数据库保存一直
     * 缓存一致性
     * 1）、双写模式
     * 2）、失效模式
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {

        /**
         * 1、占分布式锁，去redis占坑
         */
        //锁的名字。锁的粒度，越细越快
        //锁的粒度：具体缓存的是某个数据，11-号商品；product-11-lock
        RLock lock = redisson.getLock("catelogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb=null;
        try {
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();

        }
        return dataFromDb;

    }
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {

        /**
         * 1、占分布式锁，去redis占坑
         */
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,30,TimeUnit.SECONDS);
        if (lock){
            //枷锁成功 执行业务
            //设置过期时间
            /*redisTemplate.expire("lock",30,TimeUnit.SECONDS);*/
            Map<String, List<Catelog2Vo>> dataFromDb=null;
            try {
                dataFromDb = getDataFromDb();
            }finally {
                String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) " +
                        "else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"),
                        uuid);
            }

//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)){
//                redisTemplate.delete("lock");
//            }


            return dataFromDb;
        }{
            //加锁失败 ... 重试
            //sleep 重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDbWithRedisLock();

        }
    }



    //    从数据库中查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {

        /**
         * 只要是同一把锁，就能锁住需要这个锁的对象
         * 1、synchronized (this)：springboot所有的组件，在容器中都是单例的
         *todo 本地锁：sychronized juc（lock）   在分布式情况下想要锁住所有必须使用分布式锁
         */
        synchronized (this){
            /**
             * 得到锁以后，应该再去缓存中确定一次，如果没有才需要继续查询
             */
            return getDataFromDb();
        }

    }
    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
        if (!StringUtils.isEmpty(catelogJSON)) {
            //缓存不为空直接返回
            Map<String, List<Catelog2Vo>> parseObject = JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return parseObject;
        }


        List<CategoryEntity> allCategory = this.list(null);
        //获取所有一级目录
        List<CategoryEntity> level1Category = allCategory.stream()
                .filter(item -> item.getParentCid() == 0)
                .collect(Collectors.toList());

        Map<String, List<Catelog2Vo>> stringListMap = new HashMap<>();
        level1Category.stream().forEach(l1 -> {

//            QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("parent_cid", l1.getCatId());
            List<CategoryEntity> level2Category = getCategory(allCategory, l1.getCatId());
            List<Catelog2Vo> catelog2Vos = level2Category.stream().map(l2 -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo();
                catelog2Vo.setId(l2.getCatId().toString());
                catelog2Vo.setCatalog1Id(l1.getCatId().toString());
                catelog2Vo.setName(l2.getName());
//                QueryWrapper<CategoryEntity> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.eq("parent_cid", l2.getCatId());
                List<CategoryEntity> level3Category = getCategory(allCategory, l2.getCatId());
                List<Catelog3Vo> catelog3Vos = level3Category.stream().map(l3 -> {
                    Catelog3Vo catelog3Vo = new Catelog3Vo();
                    catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                    catelog3Vo.setId(l3.getCatId().toString());
                    catelog3Vo.setName(l3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(catelog3Vos);
                return catelog2Vo;
            }).collect(Collectors.toList());
            stringListMap.put(l1.getCatId().toString(), catelog2Vos);
        });
        String jsonString = JSON.toJSONString(stringListMap);
        redisTemplate.opsForValue().set("catelogJSON", jsonString, 1, TimeUnit.DAYS);
        return stringListMap;
    }
    private List<CategoryEntity> getCategory(List<CategoryEntity> selectList,Long parentCid){
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parentCid;
        }).collect(Collectors.toList());
        return collect;
    }

    public List<CategoryEntity> getCategoryChildren(CategoryEntity current,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream()
                .filter(categoryEntity ->
                        current.getCatId() == categoryEntity.getParentCid()
                )
                .map(menu -> {
                    menu.setChildren(getCategoryChildren(menu, all));
                    return menu;
                })
                .sorted((menu1, menu2) ->
                        (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort())
                )
                .collect(Collectors.toList());
        return collect;
    }

}
